import Vue from 'vue';

Vue.directive('drag', {
    inserted: function (el) {
      let dragDom = el; // 当前元素
      dragDom.style.position = "absolute";
      dragDom.style.cursor = "default";
	  
  
      let isOnTopBorder = false;
      let disX = 0;
      let disY = 0;
      const borderWidth = 10;
  
      //判断鼠标位置改变鼠标样式
      const checkMousePosition = function (e) {
        const rect = dragDom.getBoundingClientRect();
        const isOnTopBorder = e.clientY >= rect.top && e.clientY <= rect.top + borderWidth;
        if (isOnTopBorder) {
          dragDom.style.cursor = 'move';
        } else {
          dragDom.style.cursor = 'default';
        }
      };
      dragDom.addEventListener('mousemove', checkMousePosition);
  
      dragDom.onmousedown = function (e) {
        const rect = dragDom.getBoundingClientRect();
        // 判断鼠标是否在边框范围内
        isOnTopBorder = e.clientY >= rect.top && e.clientY <= rect.top + borderWidth;
        if (isOnTopBorder) {
          // 计算鼠标相对元素的位置
          disX = e.clientX - dragDom.offsetLeft;
          disY = e.clientY - dragDom.offsetTop;
          // 绑定事件
          document.onmousemove = function (e) {
            let left = e.clientX - disX;
            let top = e.clientY - disY;
            dragDom.style.left = left + 'px';
            dragDom.style.top = top + 'px';
          };
          document.onmouseup = function () {
            document.onmousemove = null;
            document.onmouseup = null;
          };
        }
      };
    }
});

export default Vue;